package com.fxf.srb.sms.controller;

import com.fxf.common.exception.Assert;
import com.fxf.common.result.R;
import com.fxf.common.result.ResponseEnum;
import com.fxf.common.util.RandomUtils;
import com.fxf.common.util.RegexValidateUtils;
import com.fxf.srb.sms.client.CoreUserInfoClient;
import com.fxf.srb.sms.service.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 饭小范
 * @version 1.0
 * @description: TODO
 * @date 2021/5/29 12:07
 */
@RestController
@RequestMapping("/api/sms")
@Api(tags = "短信管理")
@CrossOrigin //跨域
@Slf4j
public class ApiSmsController {
    @Resource
    private SmsService smsService;

    @Resource
    private CoreUserInfoClient coreUserInfoClient;

    @Resource
    private RedisTemplate redisTemplate;
    @ApiOperation("获取验证码")
    @GetMapping("/send/{mobile}")
    public R send( @ApiParam(value = "邮箱号", required = true)
                       @PathVariable String mobile){
        log.info("邮件发送");
//        Assert.notNull(mobile, ResponseEnum.MOBILE_NULL_ERROR);
        Assert.notEmpty(mobile,ResponseEnum.Email_NULL_ERROR);
        Assert.isTrue(RegexValidateUtils.checkEmail(mobile),ResponseEnum.Email_ERROR);
//        Assert

        /**
         * 远程调用service-core微服务接口校验手机号是否注册
         */
        boolean b = coreUserInfoClient.checkMobile(mobile);
        Assert.isTrue(b == false,ResponseEnum.MOBILE_EXIST_ERROR);

        Map<String,Object> param = new HashMap<>();
        //获取六位数验证码
        String code = RandomUtils.getFourBitRandom();
        param.put("code",code);
        smsService.sendMail(mobile,param);
        redisTemplate.opsForValue().set("srb:mail:code:" + mobile,code,5, TimeUnit.MINUTES );
        return R.ok().message("验证码发送成功");

    }


}
